import api from '@/api'
import cefsharpAdapter from '@/api/cefsharp'
import { userAPI } from '@/api/TabAxios/user'

const state = {
    token: localStorage.token,
    failuretime: localStorage.failuretime,
    userInfo: JSON.parse(localStorage.userInfo || '{}')
}

const getters = {
    isLogin: state => {
        let retn = false
        if (state.token != null) {
            let unix = Date.parse(new Date())
            if (unix < state.failuretime * 1000) {
                retn = true
            }
        }
        return retn
    },
    getUserInfo: state => state.userInfo
}

const actions = {
    // 登录方法 - 支持CEFSharp和默认登录
    login({
        commit
    }, loginData = null) {
        return new Promise((resolve, reject) => {
            console.log('🔐 [Token Store] 开始登录流程:', { loginData, isCefSharp: cefsharpAdapter.checkEnvironment() })
            
            // 如果有登录数据且CEFSharp环境可用，使用CEFSharp登录
            if (loginData && cefsharpAdapter.checkEnvironment()) {
                console.log('🔐 [Token Store] 使用CEFSharp登录')
                userAPI.login(JSON.stringify(loginData))
                    .then(response => {
                        console.log('✅ [Token Store] CEFSharp登录成功:', response)
                        
                        if (response.code === 0) {
                            // 处理CEFSharp返回的数据格式
                            const tokenData = {
                                token: response.token || response.data?.token || 'cefsharp_token_' + Date.now(),
                                failuretime: response.failuretime || response.data?.failuretime || (Date.parse(new Date()) / 1000 + 24 * 60 * 60),
                                userInfo: response.userInfo || response.data?.userInfo || {
                                    username: loginData.username,
                                    loginTime: new Date().toISOString(),
                                    loginType: 'cefsharp'
                                }
                            }
                            
                            commit('setData', tokenData)
                            resolve(response)
                        } else {
                            console.log('❌ [Token Store] CEFSharp登录失败:', response.msg)
                            reject(new Error(response.msg || '登录失败'))
                        }
                    })
                    .catch(error => {
                        console.error('❌ [Token Store] CEFSharp登录失败:', error)
                        reject(error)
                    })
            } else {
                // 使用默认登录逻辑
                console.log('🔐 [Token Store] 使用默认登录')
                const tokenData = {
                    token: 'default_token_' + Date.now(),
                    failuretime: Date.parse(new Date()) / 1000 + 24 * 60 * 60,
                    userInfo: {
                        username: loginData?.username || 'admin',
                        loginTime: new Date().toISOString(),
                        loginType: 'default'
                    }
                }
                
                commit('setData', tokenData)
                resolve(tokenData)
            }
        })
    },
    
    // 登出方法
    logout({
        commit
    }) {
        return new Promise((resolve, reject) => {
            console.log('🚪 [Token Store] 开始登出流程', reject)
            
            // 如果CEFSharp环境可用，调用CEFSharp登出
            if (api.cefsharp.isAvailable()) {
                console.log('🚪 [Token Store] 使用CEFSharp登出')
                api.cefsharp.user.logout()
                    .then(() => {
                        console.log('✅ [Token Store] CEFSharp登出成功')
                        commit('clearData')
                        resolve()
                    })
                    .catch(error => {
                        console.error('❌ [Token Store] CEFSharp登出失败:', error)
                        // 即使CEFSharp登出失败，也清除本地数据
                        commit('clearData')
                        resolve()
                    })
            } else {
                // 默认登出逻辑
                console.log('🚪 [Token Store] 使用默认登出')
                commit('clearData')
                resolve()
            }
        })
    },
    
    // 验证token有效性
    verifyToken({
        commit,
        state
    }) {
        return new Promise((resolve, reject) => {
            if (!state.token) {
                reject(new Error('无token'))
                return
            }
            
            // 如果CEFSharp环境可用，使用CEFSharp验证
            if (api.cefsharp.isAvailable()) {
                api.cefsharp.user.verifyToken({ token: state.token })
                    .then(response => {
                        if (response.valid) {
                            resolve(response)
                        } else {
                            commit('clearData')
                            reject(new Error('token已失效'))
                        }
                    })
                    .catch(error => {
                        console.error('❌ [Token Store] token验证失败:', error)
                        commit('clearData')
                        reject(error)
                    })
            } else {
                // 默认验证逻辑 - 检查过期时间
                const unix = Date.parse(new Date())
                if (unix < state.failuretime * 1000) {
                    resolve({ valid: true })
                } else {
                    commit('clearData')
                    reject(new Error('token已过期'))
                }
            }
        })
    }
}

const mutations = {
    setData(state, data) {
        localStorage.setItem('token', data.token)
        localStorage.setItem('failuretime', data.failuretime)
        if (data.userInfo) {
            localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
            state.userInfo = data.userInfo
        }
        state.token = data.token
        state.failuretime = data.failuretime
    },
    
    clearData(state) {
        localStorage.removeItem('token')
        localStorage.removeItem('failuretime')
        localStorage.removeItem('userInfo')
        state.token = null
        state.failuretime = null
        state.userInfo = {}
    },
    
    updateUserInfo(state, userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        state.userInfo = userInfo
    }
}

export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations
}
